package com.zja.www.view;

import com.zja.www.bean.Result;
import com.zja.www.controller.BaseController;
import com.zja.www.controller.DoctorController;
import com.zja.www.entity.Doctor;
import com.zja.www.entity.MedicalRecord;
import com.zja.www.entity.Schedule;
import com.zja.www.service.DoctorService;
import com.zja.www.service.MedicalRecordService;
import com.zja.www.service.ScheduleService;
import com.zja.www.service.UserService;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;

public class DoctorView extends BaseController {
    private final DoctorController controller;
    private final ScheduleService scheduleService;
    private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    private final SimpleDateFormat dateOnlyFormat = new SimpleDateFormat("yyyy-MM-dd");
    private Doctor currentDoctor;
    private  int currentDoctorId;

    public DoctorView(UserService userService,
                      DoctorService doctorService,
                      MedicalRecordService medicalRecordService,
                      ScheduleService scheduleService,
                      DoctorController controller,
                      Doctor currentDoctor) {
        super(userService, doctorService, medicalRecordService);
        this.scheduleService = scheduleService;
        this.controller = controller;
        this.currentDoctor = currentDoctor;
        this.currentDoctorId = currentDoctor.getId();
    }


    public void showDoctorMenu(DoctorView doctorView) {
        Scanner scanner = new Scanner(System.in);
        while (true) {
            System.out.println("\n==========医生界面============");
            System.out.println("1. 登录");
            System.out.println("0. 返回主菜单");
            System.out.print("请选择：");

            int choice = scanner.nextInt();
            scanner.nextLine();

            switch (choice) {
                case 1:
                    doctorView.showLogin();
                    break;
                case 0:
                    return;
                default:
                    System.out.println("输入无效，请重新选择！");
            }
        }
    }

    public void showLogin() {
        System.out.println("\n============医生登录界面==============");
        System.out.print("请输入姓名：");
        String name = controller.readStringInput();

        System.out.print("请输入密码：");
        String password = controller.readStringInput();

        Result result = controller.login(name, password);
        if (result.isSuccess()) {
            Doctor doctor = (Doctor) result.getData();
            this.currentDoctorId = doctor.getId();

            DoctorView doctorView = new DoctorView(
                    userService,
                    doctorService,
                    medicalRecordService,
                    scheduleService,
                    controller,
                    doctor);

            System.out.println(result.getMessage());
            doctorView.showMainMenu();
        } else {
            System.out.println("登录失败：" + result.getMessage());
        }
    }

    private void showMainMenu() {
        while (true) {
            System.out.println("\n===============医生菜单界面==================");
            System.out.println("1. 查看排班");
            System.out.println("2. 查看挂号记录");
            System.out.println("3. 修改挂号状态");
            System.out.println("4. 修改账号密码");
            System.out.println("0. 退出登录");
            System.out.print("请选择：");

            int choice = controller.readIntInput();

            switch (choice) {
                case 1:
                    showScheduleMenu();
                    break;
                case 2:
                    showRegistrationRecords();
                    break;
                case 3:
                    showUpdateStatus();
                    break;
                case 4:
                    showChangeDoctorPassword();
                    break;
                case 0:
                    controller.logout();
                    System.out.println("已退出登录");
                    return;
                default:
                    System.out.println("输入无效，请重新选择！");
            }
        }
    }

    private void showScheduleMenu() {
        while (true) {
            System.out.println("\n============查看排班界面================");
            System.out.println("1. 查看我的所有排班");
            System.out.println("2. 按日期查询排班");
            System.out.println("0. 返回医生菜单");
            System.out.print("请选择：");

            int choice = controller.readIntInput();

            switch (choice) {
                case 1:
                    showAllSchedules();
                    break;
                case 2:
                    showSchedulesByDate();
                    break;
                case 0:
                    return;
                default:
                    System.out.println("输入无效，请重新选择！");
            }
        }
    }

    private void showAllSchedules() {
        List<Schedule> schedules = scheduleService.getSchedulesByDoctor(currentDoctorId);
        displaySchedules(schedules, "我的所有排班");
    }

    private void showSchedulesByDate() {
        System.out.print("请输入查询日期(YYYY-MM-DD)：");
        String dateStr = controller.readStringInput() + " 00:00:00";

        try {
            Timestamp date = Timestamp.valueOf(dateStr);
            List<Schedule> schedules = scheduleService.getSchedulesByDoctor(currentDoctorId).stream()
                    .filter(s -> dateOnlyFormat.format(s.getDate()).equals(dateOnlyFormat.format(date)))
                    .collect(Collectors.toList());
            displaySchedules(schedules, dateStr.split(" ")[0] + "的排班");
        } catch (Exception e) {
            System.out.println("日期格式错误！");
        }
    }

    private void displaySchedules(List<Schedule> schedules, String title) {
        System.out.println("\n===== " + title + " =====");
        if (schedules.isEmpty()) {
            System.out.println("暂无排班记录");
            return;
        }

        System.out.printf("%-8s%-12s%-12s%-12s%-12s%-12s\n",
                "ID", "日期", "开始时间", "结束时间", "最大预约数", "已预约数");

        for (Schedule schedule : schedules) {
            System.out.printf("%-8d%-12s%-12s%-12s%-12d%-12d\n",
                    schedule.getId(),
                    dateOnlyFormat.format(schedule.getDate()),
                    schedule.getStartTime(),
                    schedule.getEndTime(),
                    schedule.getMaxAppointments(),
                    schedule.getBookedAppointments());
        }
    }

    private void showRegistrationRecords() {
        while (true) {
            System.out.println("\n============查看挂号记录界面===============");
            System.out.println("1. 查看今日挂号");
            System.out.println("2. 按日期查询挂号");
            System.out.println("0. 返回医生菜单");
            System.out.print("请选择：");

            int choice = controller.readIntInput();

            switch (choice) {
                case 1:
                    showTodayRegistrations();
                    break;
                case 2:
                    showRegistrationsByDate();
                    break;
                case 0:
                    return;
                default:
                    System.out.println("输入无效，请重新选择！");
            }
        }
    }

    private void showTodayRegistrations() {
        List<MedicalRecord> records = medicalRecordService.getRecordsByDoctorAndDate(
                currentDoctorId, new Timestamp(System.currentTimeMillis()));
        displayMedicalRecords(records, "今日挂号记录");
    }

    private void showRegistrationsByDate() {
        System.out.print("请输入查询日期(YYYY-MM-DD)：");
        String dateStr = controller.readStringInput() + " 00:00:00";

        try {
            Timestamp date = Timestamp.valueOf(dateStr);

            List<MedicalRecord> records = medicalRecordService.getRecordsByDoctorAndDate(currentDoctorId, date);
            displayMedicalRecords(records, dateStr.split(" ")[0] + "的挂号记录");
        } catch (Exception e) {
            System.out.println("日期格式错误！");
        }
    }

    private void displayMedicalRecords(List<MedicalRecord> records, String title) {
        System.out.println("\n===== " + title + " =====");
        if (records.isEmpty()) {
            System.out.println("暂无挂号记录");
            return;
        }

        System.out.printf("%-8s%-12s%-12s%-20s%-12s\n",
                "ID", "患者ID", "类型", "预约时间", "状态");

        for (MedicalRecord record : records) {
            System.out.printf("%-8d%-12d%-12s%-20s%-12s\n",
                    record.getId(),
                    record.getUserId(),
                    record.getType(),
                    dateFormat.format(record.getRecordTime()),
                    record.getStatus());
        }
    }


    private void showUpdateStatus() {
        List<MedicalRecord> records = controller.getTodayRecords();
        if (records.isEmpty()) {
            System.out.println("今日没有挂号记录");
            return;
        }

        displayRecords(records, "今日挂号记录");
        System.out.print("请输入要修改的记录ID：");
        int recordId = controller.readIntInput();

        System.out.println("请选择新状态：");
        System.out.println("1. 待确认 (pending)");
        System.out.println("2. 已确认 (confirmed)");
        System.out.println("3. 已取消 (cancelled)");
        System.out.println("4. 已完成 (completed)");
        System.out.print("请选择：");

        int statusChoice = controller.readIntInput();
        String newStatus = switch (statusChoice) {
            case 1 -> MedicalRecord.STATUS_PENDING;
            case 2 -> MedicalRecord.STATUS_CONFIRMED;
            case 3 -> MedicalRecord.STATUS_CANCELLED;
            case 4 -> MedicalRecord.STATUS_COMPLETED;
            default -> null;
        };

        if (newStatus != null && controller.updateRecordStatus(recordId, newStatus)) {
            System.out.println("状态更新成功");
        } else {
            System.out.println("状态更新失败");
        }
    }

    private void displayRecords(List<MedicalRecord> records, String title) {
        System.out.println("\n===== " + title + " =====");
        if (records.isEmpty()) {
            System.out.println("暂无记录");
            return;
        }

        System.out.printf("%-8s%-12s%-12s%-20s%-12s\n",
                "ID", "用户ID", "类型", "时间", "状态");

        for (MedicalRecord record : records) {
            System.out.printf("%-8d%-12d%-12s%-20s%-12s\n",
                    record.getId(),
                    record.getUserId(),
                    record.getType(),
                    dateFormat.format(record.getRecordTime()),
                    record.getStatus());
        }
    }

    /**
     * 显示修改医生密码界面
     */
    private void showChangeDoctorPassword() {

        System.out.println("\n================医生修改密码界面==================");
        System.out.print("请输入当前密码：");
        String currentPassword = readStringInput();


        if (!currentPassword.equals(currentDoctor.getPassword())) {
            System.out.println("当前密码错误！");
            showMainMenu();
            return;
        }

        System.out.print("请输入新密码：");
        String newPassword = readStringInput();
        System.out.print("再次确认密码：");
        String confirmPassword = readStringInput();

        if (!newPassword.equals(confirmPassword)) {
            System.out.println("您两次输入的密码不一致，是否重新输入(y/n)");
            String choice = readStringInput().toLowerCase();
            if (choice.equals("y")) {
                showChangeDoctorPassword();
            } else {
                showMainMenu();
            }
            return;
        }

        // 调用医生控制器的更新密码方法
        Result result = controller.updatePassword(currentDoctor.getId(), newPassword);
        if (result.isSuccess()) {
            currentDoctor.setPassword(newPassword);
            System.out.println("医生密码修改成功！");
        } else {
            System.out.println("医生密码修改失败：" + result.getMessage());
        }
        showMainMenu();
    }



}
